using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using Infragistics.Controls.Grids;
using Infragistics.Controls.Grids.Primitives;

namespace ibba.src.noriskbo.code.behavior
{

    public class XamGridBehavior : Behavior<XamGrid>
    {

        //public event EventHandler<CellClickedEventArgs> RowGroupedExpander;

        public delegate void ReloadColumnsEventHandler(ColumnBaseCollection pColumns);
        public event ReloadColumnsEventHandler ReloadedColumns;

        private bool _rowInExpansion;
        private bool _keyCtrlPress;
        private bool _layoutUpdated;
        private bool _translated;
        private List<Column> _groupedColumns;
        private List<ColumnBase> _visibleColumns;

        protected override void OnAttached()
        {
            base.OnAttached();

            if (AssociatedObject != null)
            {
                AssociatedObject.Loaded += OnLoaded;
                AssociatedObject.Unloaded += OnUnloaded;
            }
        }

        protected override void OnDetaching()
        {
            if (AssociatedObject != null)
            {
                AssociatedObject.Loaded -= OnLoaded;
                AssociatedObject.Unloaded -= OnUnloaded;
            }

            base.OnDetaching();
        }

        public bool IsExpandRowGrouped { get; set; }
        public bool IsExpandOnlyOne { get; set; }
        public bool IsHeaderCopyToClibboard { get; set; }

        public XamGrid Source { get; private set; }

        void OnLoaded(object sender, System.Windows.RoutedEventArgs e)
        {
            this.Source = ((XamGrid)sender);

            this.Source.CellDoubleClicked += OnCellDoubleClicked;
            this.Source.RowExpansionChanged += OnRowExpansionChanged;
            this.Source.KeyDown += OnKeyDown;
            this.Source.KeyUp += OnKeyUp;
            this.Source.LayoutUpdated += OnLayoutUpdated;
        }


        void OnUnloaded(object sender, System.Windows.RoutedEventArgs e)
        {
            this.Source.CellDoubleClicked -= OnCellDoubleClicked;
            this.Source.RowExpansionChanged -= OnRowExpansionChanged;
            this.Source.KeyDown -= OnKeyDown;
            this.Source.KeyUp -= OnKeyUp;
            this.Source.LayoutUpdated -= OnLayoutUpdated;
        }

        void OnLayoutUpdated(object sender, EventArgs e)
        {
            if (!_layoutUpdated)
            {
                _layoutUpdated = true;
                SaveColumnConfiguration();
            }

            if (!_translated)
            {
                _translated = (_layoutUpdated && this.Source.ItemsSource != null);

                if (_translated)
                {
                    XamGridHelper.TraduzirFiltro(this.Source);
                    XamGridHelper.TraduzirSummary(this.Source);
                }

            }

        }

        void OnCellDoubleClicked(object sender, CellClickedEventArgs e)
        {
            if (e.Cell.Row.RowType == RowType.GroupByRow)
            {

                if (this.IsExpandRowGrouped)
                {
                    var groupByRow = ((GroupByRow)e.Cell.Row);
                    groupByRow.IsExpanded = !groupByRow.IsExpanded;

                    //if (RowGroupedExpander != null)
                    //    RowGroupedExpander(sender, e);

                }

            }
        }


        void OnRowExpansionChanged(object sender, RowExpansionChangedEventArgs e)
        {

            if (this.IsExpandOnlyOne && !_rowInExpansion)
            {
                _rowInExpansion = e.Row.IsExpanded;

                if (_rowInExpansion)
                {
                    foreach (var item in ((XamGrid)sender).Rows)
                    {
                        if (item.IsExpanded)
                            item.IsExpanded = false;
                    }

                    //e.Row.IsExpanded = true;

                    ActiveRowExpander(e.Row);
                    _rowInExpansion = false;
                }
            }
        }

        void ActiveRowExpander(RowBase p)
        {
            Row r = ((Row)p);

            r.IsExpanded = true;

            if (r.ParentRow != null)
                ActiveRowExpander(((Row)r.ParentRow));

        }

        void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Ctrl)
                _keyCtrlPress = true;

            if (_keyCtrlPress && e.Key == Key.C)
            {
                CopyToClipboard(sender as XamGrid);
            }
        }

        void OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Ctrl)
                _keyCtrlPress = false;
        }

        private void CopyToClipboard(XamGrid pGrid)
        {
            if (pGrid.SelectionSettings.SelectedRows.Count == 0) return;

            StringBuilder clipboard = new StringBuilder();

            if (pGrid.SelectionSettings.SelectedRows.Count > 0)
            {
                if (this.IsHeaderCopyToClibboard)
                {
                    foreach (Column item in pGrid.Columns.DataColumns)
                    {
                        if (item != null && item.DataType.FullName != "System.Object")
                            if (item.Visibility == Visibility.Visible)
                            {
                                clipboard.Append(item.HeaderText);
                                clipboard.Append("\t");
                            }
                    }

                    clipboard.Append("\r\n");
                }

                foreach (Row row in pGrid.SelectionSettings.SelectedRows)
                {
                    foreach (Column item in row.Columns.DataColumns)
                    {
                        if (item.DataType.FullName != "System.Object")
                            if (item.Visibility == Visibility.Visible)
                            {
                                if (row.Cells[item].Value == null)
                                    clipboard.Append("");
                                else
                                    clipboard.Append(row.Cells[item].Value.ToString());

                                clipboard.Append("\t");
                            }

                    }

                    clipboard.Append("\r\n");
                }
            }

            ClipboardHelper.SetText(clipboard.ToString());
        }


        public void SaveColumnConfiguration()
        {

            if (this.Source.Columns.Count > 0)
            {

                _visibleColumns = this.Source.Columns.Where(w => w.Visibility == Visibility.Visible).ToList();
                _groupedColumns = this.Source.GroupBySettings.GroupByColumns.ToList();
                //_groupedColumns = this.Source.GroupBySettings.GroupByColumns.Where(w => w.Visibility == Visibility.Visible).ToList();

            }
        }

        public void ReloadColumnConfiguration()
        {
            this.Source.FilteringSettings.RowFiltersCollection.Clear();
            this.Source.SortingSettings.SortedColumns.Clear();
            this.Source.GroupBySettings.GroupByColumns.Clear();

            if (_visibleColumns != null)
                foreach (ColumnBase item in this.Source.Columns)
                {
                    if (_visibleColumns.Contains(item))
                        item.Visibility = Visibility.Visible;
                    else
                        item.Visibility = Visibility.Collapsed;
                }


            if (_groupedColumns != null)
                foreach (Column item in _groupedColumns)
                {
                    this.Source.GroupBySettings.GroupByColumns.Add(item);
                }


            if (ReloadedColumns != null)
                ReloadedColumns(this.Source.Columns);

        }
    }


}
